//
//  GJFJSPatchManager.m
//  Wedding
//
//  Created by Marx on 2017/1/8.
//  Copyright © 2017年 郭静芬. All rights reserved.
//

#import "GJFJSPatchManager.h"
#import "RSA.h"
#define PUBLIC_KEY @"-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDF26Xnu4A+vjg3nvId6O5+b13B RRFnxpoY5T8nDIP3IgqrdgGtQtct3aoXCanZDT4UtZ891mUL5E9gJjwFmwX6COXu iHTQtc7T/PyB6qPUv1q72wZFUMFEQB/Lj1UORpsZL4njrMkeI39Mt+/p9fW6WuUE VBd1TUH+Q4RkrvoJXwIDAQAB -----END PUBLIC KEY-----"

typedef void(^POSTBLOCK)(NSError *error, id response);

@implementation GJFJSPatchManager
#pragma mark - 执行js热修复脚本
/**
 * 判断上次成功请求下载的时间
 * ①. 项目本地是否有js文件，有则执行脚本，并继续②。否则跳过本次操作
 * ②. 如果连续崩溃超过1次，执行本地补丁。否则删除本地补丁
 *
 **/
//+ (void)execJSPatch {
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    BOOL isDir;
//    if ([fileManager fileExistsAtPath:scriptPath isDirectory:&isDir]) {
//        [JPEngine startEngine];
//        NSString *script = [NSString stringWithContentsOfFile:scriptPath encoding:NSUTF8StringEncoding error:nil];
//        [JPEngine evaluateScript:script];
//    };
//}


#pragma mark - 下载js热修复脚本
/**
 * 判断上次成功请求下载的时间
 * ①. 如果超过1小时(3600s)，则②。否则跳过本次操作
 * ②. 请求判断是否需要更新(isUpdate)，则需要记录code码，并继续③。否则跳过本次操作
 * ③. 下载最新的js文件
 * ④. 校验code是否匹配，匹配则保存到本地，否则跳过本次操作
 *
 **/
+ (void)downloadJSPatch {
    // 上次请求时间
    NSTimeInterval lastReqTime = [[NSUserDefaults standardUserDefaults] doubleForKey:kLastReqTime];
    // 本次请求时间
    NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970];
    // ①
    if ((nowTime - lastReqTime) < 3600 && lastReqTime != 0) {
        NSLog(@"请求脚本时间过短");
        return;
    }
//    [[NSUserDefaults standardUserDefaults] setDouble:[[NSDate date] timeIntervalSince1970] forKey:kLastReqTime];
    NSDictionary *dict = @{@"":@""};
    [[self class] postRequestWithUrl:kIsNeedUrl param:dict complete:^(NSError *error, id response) {
        if (error) {
            NSLog(@"检测更新失败");
        }
        else if([[response objectForKey:@"code"] intValue] != 1000 || ![[[response objectForKey:@"data"] objectForKey:@"isUpdate"] boolValue]) {
            NSLog(@"没有更新");
        }
        else {
            // 去下载
            NSString *downloadUrl = [[response objectForKey:@"data"] objectForKey:@"downUrl"];
            if (!downloadUrl) {
                return;
            }
            [[self class] postRequestWithUrl:downloadUrl param:dict complete:^(NSError *error, id response) {
                if (error || [[response objectForKey:@"code"] intValue] != 1000) {
                    NSLog(@"下载脚本失败");
                    return;
                }
                else {
                    NSString *code = response[@"data"][@"code"];
                    NSString *Cc = [RSA decryptString:code publicKey:PUBLIC_KEY];
                    NSLog(@"-++++-%@", Cc);
                    if (!code) {
                        NSLog(@"第三方脚本注入");
                    }
                    else {
                        NSLog(@"脚本下载成功");
                        NSString *script = response[@"data"][@"script"];
                        [script writeToFile:scriptPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
                    }
                }

            }];
        }
    }];
    
    /* NSURLConnection请求，iOS9已经废弃
    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://cnbang.net/test.js"]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSString *script = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [JPEngine evaluateScript:script];
    }];
    */
}

+ (void)postRequestWithUrl:(NSString *)urlStr param:(NSDictionary *)param complete:(POSTBLOCK)complete {
    //1.创建URL
    NSURL *url = [NSURL URLWithString:urlStr];
    
    //2.创建请求
    NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url];
    //2.5 核心设置boby
//    NSString *bobyString = POST_BODY;
    
    NSData *postData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
    [mutableRequest setHTTPMethod:@"POST"];
    [mutableRequest setHTTPBody:postData];
    
    // 3.创建Session对象
    NSURLSession *session = [NSURLSession sharedSession];
    
    // 4.创建task
    NSURLSessionTask *task = [session dataTaskWithRequest:mutableRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            return;
        }
        id res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        complete(error, res);
    }];
    
    //6.启动任务
    [task resume];
}

@end
